package com.rp.user.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.rp.bo.RegistLoginBO;
import com.rp.news.common.NewsCommon;
import com.rp.news.common.RedisCommon;
import com.rp.news.common.ResponseStatusEnum;
import com.rp.news.common.Result;
import com.rp.news.enums.UserStatus;
import com.rp.news.util.AliyunCmsUtils;
import com.rp.news.util.CommonUtil;
import com.rp.news.util.IPUtil;
import com.rp.news.util.RedisOperator;
import com.rp.pojo.AppUser;
import com.rp.user.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@RestController
@Slf4j
@Api(value = "用户登录注册", tags = {"用户登录注册congtroller api文档"})
@RequestMapping("/passport")
public class PassportController {


    @Autowired
    private AliyunCmsUtils cmsUtils;

    @Autowired
    private UserService userService;

    @Autowired
    public RedisOperator redis;

    @Autowired
    private CommonUtil commonUtil;


    @ApiOperation(value = "测试发送短信接口", notes = "测试发送短信接口", httpMethod = "GET")
    @GetMapping("/getSMSCode")
    public Result getSmsCode(String mobile, HttpServletRequest request) {
        String code = RandomUtil.randomNumbers(6);
        String requestIp = IPUtil.getRequestIp(request);
        redis.setnx60s(NewsCommon.SMS_CODE + ":" + requestIp, requestIp);

        log.info("验证码 code= {}", code);
        //cmsUtils.sendSms(NewsCommon.mobile,code);
        redis.set(NewsCommon.SMS_CODE + ":" + mobile, code, 5 * 60);
        return Result.ok();
    }

    @ApiOperation(value = "一键登录接口", notes = "一键登录接口", httpMethod = "POST")
    @PostMapping("/doLogin")
    public Result doLogin(@RequestBody @Valid RegistLoginBO registLoginBO, HttpServletRequest request, HttpServletResponse response) {

        String mobile = registLoginBO.getMobile();
        String smsCode = registLoginBO.getSmsCode();

        String redisSmsCode = redis.get(NewsCommon.SMS_CODE + ":" + mobile);

        //验证redis
        if (StrUtil.isBlank(redisSmsCode) || !ObjectUtil.equal(smsCode, redisSmsCode)) {
            return Result.errorCustom(ResponseStatusEnum.SMS_CODE_ERROR);
        }
        //查询数据库获取用户信息

        AppUser appUser = userService.queryIsExistByMobile(mobile);
        if (appUser == null) {
            //return  Result.errorCustom(ResponseStatusEnum.USER_NOT_EXIST_ERROR);
            //用户不存在 直接注册
            appUser = userService.createUser(mobile);
        }

        if (appUser.getActiveStatus() == UserStatus.FROZEN.type) {
            return Result.errorCustom(ResponseStatusEnum.USER_FROZEN);
        }

        Integer activeStatus = appUser.getActiveStatus();
        if (UserStatus.FROZEN.type != activeStatus) {
            String utoken = IdUtil.fastSimpleUUID();
            redis.set(RedisCommon.REDIS_USER_TOKEN + ":" + appUser.getId(), utoken);
            redis.set(RedisCommon.REDIS_USER_INFO + ":" + appUser.getId(), JSONUtil.toJsonStr(appUser));

            //将用户id 和token 保存到cookie中
            commonUtil.setCookie(request, response, "utoken", utoken, NewsCommon.COOKIE_MONTH);
            commonUtil.setCookie(request, response, "uid", appUser.getId(), NewsCommon.COOKIE_MONTH);

        }
        redis.del(NewsCommon.SMS_CODE + ":" + mobile);
        return Result.ok(appUser);
    }

    @ApiOperation(value = "退出登录", notes = "退出登录", httpMethod = "POST")
    @PostMapping("/logout")
    public Result logout(String userId, HttpServletRequest request, HttpServletResponse response) {
        redis.del(RedisCommon.REDIS_USER_TOKEN + ":" + userId);
        commonUtil.setCookie(request, response, "utoken", "", 0);
        commonUtil.setCookie(request, response, "uid", "", 0);

        return Result.ok();
    }


}
